
class MyModal {
    constructor() {
        let el = 'mymodal';
        this.container = document.querySelector('#'+el);
        if(!this.container) {
            this.createContainer(el);
        }
    }

    //创建Container
    createContainer(el) {
        let container = document.createElement('div');
        container.setAttribute('id',el);
        container.style.position = 'absolute';
        container.style.display = 'block';
        container.style.top = '0';
        container.style.right = '0';
        container.style.bottom = '0';
        container.style.left = '0';
        container.style.zIndex = '99';
        container.style.transition = 'background .35s';
        container.style.background = 'rgba(0,0,0,0)';
        this.container = container;
        document.body.appendChild(this.container);
    }

    //显示Container
    showContainer() {
        //为了触发transition
        setTimeout(() => {
            this.container.style.background = 'rgba(0,0,0,.2)';
        })
    }
    //隐藏Container
    hideContainer() {
        this.container.style.background = 'rgba(0,0,0,0)';
    }

    //移除Container
    closeContainer() {
        this.hideContainer();
        setTimeout(() => {
            document.body.removeChild(this.container);
        },300)
    }

    //显示对话框
    showDialog(str,callback) {
        let html = `
            <div class="mymodal-container">
            <div class="mymodal-content">`+str+`</div>
            <div class="mymodal-op bd-top-1px">
                <span class="op-item op-item-no">不同意</span>
                <span class="op-item op-item-yes">同意</span>
            </div>
            </div>
        `;
        this.container.innerHTML = html;
        this.showContainer();

        let opno = document.querySelector('.op-item-no'),
            opyes = document.querySelector('.op-item-yes');
        opno.addEventListener('click', () =>{
            this.closeDialog();
            this.closeContainer();
        })
        opyes.addEventListener('click', () =>{
            callback();
            this.closeContainer();
        })
    }
    
    //关闭对话框
    closeDialog() {
        let mymodalContainer = document.querySelector('.mymodal-container');
        mymodalContainer.style.animationName = 'modalani-close';
        //为了触发关闭动画
        setTimeout(() => {
            mymodalContainer.style.display = 'none';
        },300)  //注意时间要小于动画modalani-close的执行时间，否则会出现闪烁
    }
}

module.exports  = MyModal;